06. Type Casting

Type Casting

ND079 C1 L1 A05 Type Casting

Type casting is changing one type into another type. There are two kinds of type casting: Automatic and manual.

Automatic Type Casting

Automatic type casting converts a smaller type into a larger type. For example:

int intNumber = 3;
double doubleNumber = intNumber;
System.out.println(doubleNumber);

When we print doubleNumber, the value will be 3.0. Notice that there is no precision lost going from a smaller type into a larger type. We started with 3 and ended up with 3.0.

Manual Type Casting

Manual type casting is necessary when we want to do either of these things:

  • Convert a larger type into a smaller type
  • Convert one object type into another

For example, here we are converting from a larger type (double) to a smaller type (int):

double doubleNumber = 3.5;
int intNumber = (int)doubleNumber;
System.out.println(intNumber);

The resulting value will be 3, not 3.5. When we go from a larger type into a smaller type, precision is lost. Java cuts off additional data that will not fit in the casted type. So when we go from a double to an int, any values that are not integers will be removed. This is called truncation.

Consider this code:

double x = 35.7;
int y = (int)x;

If we print the value of y, what would we get?

SOLUTION: 35